package com.yunmaozj.tools.site.server.controller;

import com.yunmaozj.tools.site.server.config.ResourceCacheManager;
import com.yunmaozj.tools.site.server.dto.DocsList;
import com.yunmaozj.tools.site.server.util.FileManager;
import com.yunmaozj.tools.site.server.util.SiteMetadata;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author zhongminghong
 * @email zhongmh@yunmaozj.com
 * @create 2022-05-28 17:14
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/view/docs")
public class ViewController {

    private FileManager fileManager;
    private ResourceCacheManager resourceCacheManager;

    @PostMapping("login")
    public ResponseEntity<String> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) throws DocumentException {
        SiteMetadata siteMetadata = SiteMetadata.load(fileManager);
        if (siteMetadata.existsDeveloper(username, password)) {
            String sessionId = WebUtils.getCookie(request,"JSESSIONID").getValue();
            resourceCacheManager.addLoginInfo(sessionId, username);
            List<DocsList> docsLists = siteMetadata.projectList(username);
            docsLists.forEach(docsList -> resourceCacheManager.addResource(username, docsList.getProjectId()));
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    @GetMapping("docsList")
    public ResponseEntity<List<DocsList>> docsList() throws DocumentException {
        SiteMetadata siteMetadata = SiteMetadata.load(fileManager);
        List<DocsList> docsLists = siteMetadata.projectList("zhongmh");
        return ResponseEntity.ok(docsLists);
    }
}
